﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.ServiceModel;
using LoadDBWithTestData.ScanatronService;
using System.Reflection;
using System.IO;
using System.Drawing.Imaging;

namespace LoadDBWithTestData
{
    public partial class Form1 : Form
    {
        private BasicHttpBinding _binding;
        private EndpointAddress _address;
        private const string LoadData = "Load Beers, Drinkers, and Pictures";

        public Form1()
        {
            InitializeComponent();

            Uri baseAddress = new Uri(Properties.Settings.Default.ServerDb);
            lblUrl.Text = baseAddress.AbsoluteUri;
            _binding = new BasicHttpBinding();
            _address = new EndpointAddress(baseAddress);
        }

        private void btnDoesDbExist_Click(object sender, EventArgs e)
        {
            if (btnDoesDbExist.Text == LoadData)
            {
                btnLoad_Click(sender, e);
                return;
            }

            try
            {
                using (ScaningServiceClient client = new ScaningServiceClient(_binding, _address))
                {
                    var beers = client.GetBeers();

                    // Don't care about value - only that no error occurred.
                    panel1.Enabled = true;
                    lblDbExists.Text = "Endpoint ready.";

                    btnDoesDbExist.Text = LoadData;
                }
            }
            catch (Exception ex)
            {
                lblDbExists.Text = "Endpoint failure.";
                string s = ex.Message;
                if (ex.InnerException != null)
                {
                    s += "\n\nInner exception: " + ex.InnerException.Message;
                }

                MessageBox.Show(s, "Server error");
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            rtbLog.Clear();
            rtbLog.AppendText("Opening server...\n\n");

            try
            {
                using (ScaningServiceClient client = new ScaningServiceClient(_binding, _address))
                {
                    // Load all beers.
                    Beer beer = new Beer() { BarCode = "90001", Name = "Heineken Dark", Brand = "Heineken", Type = "IDK" };
                    if (client.GetBeers().Where(t => t.BarCode == beer.BarCode).Count() == 0)
                    {                     
                        rtbLog.AppendText($"Beer: {beer}\n");
                        client.AddBeer(beer);
                    }
                    else
                    {
                        rtbLog.AppendText($"Beer '{beer.Name}' already loaded.\n");
                    }

                    beer = new Beer() { BarCode = "90002", Name = "Corona Extra", Brand = "Corona", Type = "IDK" };
                    if (client.GetBeers().Where(t => t.BarCode == beer.BarCode).Count() == 0)
                    {
                        rtbLog.AppendText($"Beer: {beer}\n");
                        client.AddBeer(beer);
                    }
                    else
                    {
                        rtbLog.AppendText($"Beer '{beer.Name}' already loaded.\n");
                    }
                    
                    beer = new Beer() { BarCode = "90003", Name = "Sam Adams", Brand = "Sam Adams", Type = "IDK" };
                    if (client.GetBeers().Where(t => t.BarCode == beer.BarCode).Count() == 0)
                    {
                        rtbLog.AppendText($"Beer: {beer}\n");
                        client.AddBeer(beer);
                    }
                    else
                    {
                        rtbLog.AppendText($"Beer '{beer.Name}' already loaded.\n");
                    }

                    beer = new Beer() { BarCode = "90004", Name = "Guinness", Brand = "Guinness", Type = "IDK" };
                    if (client.GetBeers().Where(t => t.BarCode == beer.BarCode).Count() == 0)
                    {                      
                        rtbLog.AppendText($"Beer: {beer}\n\n");
                        client.AddBeer(beer);
                    }
                    else
                    {
                        rtbLog.AppendText($"Beer '{beer.Name}' already loaded.\n");
                    }

                    // Load all drinkers and their pictures.
                    LoadDrinkerAndPicture(client, "10001", "Super", "Girl", true, "Supergirl.bmp");
                    LoadDrinkerAndPicture(client, "10002", "Audrey", "Hepburn", true, "AudreyHepburn.bmp");
                    LoadDrinkerAndPicture(client, "10003", "Albert", "Einstein", true, "Einstein.bmp");
                    LoadDrinkerAndPicture(client, "10004", "Aho", "Trump", false, "Trump.bmp");

                    // Maximum of two beers.
                    //client.
                }

                rtbLog.AppendText("\nCompleted.");
            }
            catch (Exception ex)
            {
                lblDbExists.Text = "Endpoint failure.";
                string s = ex.Message;
                if (ex.InnerException != null)
                {
                    s += "\n\nInner exception: " + ex.InnerException.Message;
                }

                MessageBox.Show(s, "Server error");
            }
        }

        private void LoadDrinkerAndPicture(ScaningServiceClient client,
            string barCode, string firstName, string lastName, bool canServe, string bmpName)
        {
            ImageConverter imageConverter = new ImageConverter();

            // Create new drinker entry.
            if (client.GetDrinkers().Where(t => t.BarCode == barCode).Count() > 0)
            {
                // Already loaded.
                rtbLog.AppendText($"Drinker '{firstName} {lastName}' already loaded.\n");
                return;
            }

            Drinker drinker = new Drinker() { BarCode = barCode, FirstName = firstName, LastName = lastName, CanServe = canServe };
            rtbLog.AppendText($"Drinker: {drinker}\n");
            client.AddDrinker(drinker);

            // Get ID assigned to drinker.
            drinker = client.GetDrinkers().Where(t => t.BarCode == barCode).First();
                        
            // Add picture.
            Bitmap bm = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream("LoadDBWithTestData.Resources." + bmpName));

            // Create byte[] from image.
            MemoryStream ms = new MemoryStream();
            bm.Save(ms, ImageFormat.Bmp);
            Byte[] byteArray = ms.ToArray(); ;

            DrinkerPicture drinkerPic =
                new DrinkerPicture() { DrinkerID = drinker.Id, Picture = byteArray };
            client.AddUpdatePictures(drinkerPic);
        }
    }
}
